package service.util
{
	import model.Article;
	
	import service.events.NetworkErrorEvent;

	/**
	 * This class is used for parsing XMLs into models and models into XMLs.
	 */
	public class XMLTemplateParser
	{
		public function XMLTemplateParser(value:SingletoneEnforcer) {
			if (value == null) {
				throw new Error();
			}
		}
		
		public static function parseErrorResponse(xml:XML):NetworkErrorEvent {
			var code:int = xml.ErrorCode.@value;
			var message:String = xml.ErrorCode.@message;
			var cause:String = xml.ErrorCode.@cause;
			
			return new NetworkErrorEvent(code, message, cause);
		}
		
		public static function getLoginXML(username:String, password:String):XML {
			var xml:XML = XMLTemplate.getLoginTemplate();
			
			xml.Content.Username.@value = username;
			xml.Content.Password.@value = password;
			
			return xml;
		}
		
		public static function getLogoutXML(session:String):XML {
			var xml:XML = XMLTemplate.getLogoutTemplate();
			
			xml.Content.Session.@value = session;
			
			return xml;
		}
		
		public static function getSnippetDomaninXML(session:String):XML {
			var xml:XML = XMLTemplate.getDomainTemplate();
			
			xml.Content.Session.@value = session;
			
			return xml;
		}
		
		public static function getAddSnippetXML(session:String, title:String, domain:String, value:String, tags:String):XML {
			var xml:XML = XMLTemplate.getAddSnippetTemplate();
			
			xml.Content.Session.@value = session;
			xml.Content.Article.@title = title;
			xml.Content.Article.@domain = domain;
			xml.Content.Article.@value = value;
			var result:Array = tags.split(",");
			for(var i:int = 0 ; i<result.length; i++) {
				var s:XML = new XML("<Tag value = \""+result[i]+"\" />");
				xml.Content.Article.appendChild(s);	
			}
			
			
			return xml;
		}
		
		public static function getAllSnippetXML(session:String):XML {
			var xml:XML = XMLTemplate.getAllSnippetTemplate();
			
			xml.Content.Session.@value = session;
			
			return xml;
		}
		
		public static function manageArticle(xml:XML):Array {
			var list:XMLList = xml.Article;
			var result:Array = new Array();
			trace("lungimea vietii:",list.length());

			for (var i:int = 0; i<list.length(); i++) {
				var article:Article = new Article();
				
				article.content = list[i].@value;
				article.domain = list[i].@domain;
				article.title = list[i].@title;
				result[i] = article;
			}
			
			return result;
				
			
		}
	}
}

class SingletoneEnforcer {}